from django.db import models
from user.models import SysUser  # 使用项目的真实用户模型
from django.utils import timezone


class UserChatRoom(models.Model):
    """用户聊天室模型"""
    
    ROOM_TYPE_CHOICES = [
        ('private', '一对一'),
        ('group', '群聊'),
    ]
    
    room_type = models.CharField(
        max_length=10, 
        choices=ROOM_TYPE_CHOICES, 
        default='private',
        verbose_name='聊天室类型'
    )
    participants = models.ManyToManyField(
        SysUser, 
        related_name='chat_rooms',
        verbose_name='参与用户'
    )
    created_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name='创建时间'
    )
    updated_at = models.DateTimeField(
        auto_now=True,
        verbose_name='更新时间'
    )
    
    class Meta:
        verbose_name = '聊天室'
        verbose_name_plural = '聊天室'
        ordering = ['-updated_at']
    
    def __str__(self):
        participants_names = ", ".join([user.username for user in self.participants.all()])
        return f"聊天室 {self.id} - {self.get_room_type_display()} ({participants_names})"
    
    @property
    def last_message(self):
        """获取最后一条消息"""
        return self.messages.order_by('-timestamp').first()
    
    def get_other_participant(self, current_user):
        """获取对话中的另一个参与者（适用于一对一聊天）"""
        if self.room_type == 'private':
            return self.participants.exclude(id=current_user.id).first()
        return None


class UserChatMessage(models.Model):
    """用户聊天消息模型"""
    
    MESSAGE_TYPE_CHOICES = [
        ('text', '文本'),
        ('image', '图片'),
        ('file', '文件'),
    ]
    
    room = models.ForeignKey(
        UserChatRoom,
        on_delete=models.CASCADE,
        related_name='messages',
        verbose_name='聊天室'
    )
    sender = models.ForeignKey(
        SysUser,
        on_delete=models.CASCADE,
        related_name='sent_messages',
        verbose_name='发送者'
    )
    content = models.TextField(verbose_name='消息内容')
    message_type = models.CharField(
        max_length=10,
        choices=MESSAGE_TYPE_CHOICES,
        default='text',
        verbose_name='消息类型'
    )
    timestamp = models.DateTimeField(
        default=timezone.now,
        verbose_name='发送时间'
    )
    
    class Meta:
        verbose_name = '聊天消息'
        verbose_name_plural = '聊天消息'
        ordering = ['timestamp']
    
    def __str__(self):
        return f"{self.sender.username}: {self.content[:30]}... ({self.timestamp})"